/**
 * 
 */
package server.log;

import java.io.IOException;

import org.apache.log4j.FileAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;

import server.conf.Preferences;
import server.exception.ServerRuntimeException;

/**
 * Module responsible for logging activity in the server.
 * 
 * @author Kamil Nowak
 *
 */
public class Logging {

	private final static Logging instance = new Logging();
	
	private final static Level DEFAULT_LOG_LEVEL = Level.ALL;
	
	private static Logger mainLogger = Logger.getLogger("server");
	
	private Level logLevel =  DEFAULT_LOG_LEVEL; 
	private String logDir = Preferences.instance().getPreference("log_dir");
	private String logPattern = Preferences.instance().getPreference("log_pattern");
	
	private Logging() { 
		//mainLogger.setLevel( logLevel );
		String propLevel = Preferences.instance().getPreference("log_pattern");
		if ("all".equals(propLevel)) logLevel = Level.ALL;
		else if ("debug".equals(propLevel)) logLevel = Level.DEBUG;
		else if ("info".equals(propLevel)) logLevel = Level.INFO;
		else if ("error".equals(propLevel)) logLevel = Level.ERROR;
		else if ("off".equals(propLevel)) logLevel = Level.OFF;
		else logLevel = Level.ALL;
	}

	/**
	 * Gets standalone instance of Logging class
	 * @return standalone object
	 */
	public static Logging instance() {
		return instance;
	}
	
	/**
	 * Returns logger for main thread
	 * @return
	 */
	public Logger getMainLogger() {
		return mainLogger;
	}
	
	/**
	 * Returns logger writing to file with specified name
	 * All configured parameters are applied to the logger
	 * 
	 * @param name name of a file
	 * @return
	 */
	public Logger getLogger(String name) {
		
		Logger logger = Logger.getLogger(name);
		logger.setLevel( logLevel );
		 
	    try
	    {
	      FileAppender appender = new FileAppender (new PatternLayout(logPattern), logDir + "/" + name + ".log", true);
	      logger.addAppender (appender);
	      
	      logger.info("Logging initialized.");
	    }
	    catch(IOException e)
	    {
	      throw new ServerRuntimeException("Unable to load file " + logDir + "/" + name + ".log",e);
	    } 	
		return logger;
	}
	
}
